package com.example.keven.cn.linechart;

import android.graphics.Color;
import android.graphics.drawable.Drawable;
import android.support.v4.app.FragmentActivity;
import android.support.v4.content.ContextCompat;
import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.MotionEvent;
import android.view.WindowManager;
import android.widget.SeekBar;
import android.widget.TextView;

import com.example.keven.cn.linechart.util.MyMarkerView;
import com.github.mikephil.charting.animation.Easing;
import com.github.mikephil.charting.charts.LineChart;
import com.github.mikephil.charting.components.Legend;
import com.github.mikephil.charting.components.LimitLine;
import com.github.mikephil.charting.components.XAxis;
import com.github.mikephil.charting.components.YAxis;
import com.github.mikephil.charting.data.Entry;
import com.github.mikephil.charting.data.LineData;
import com.github.mikephil.charting.data.LineDataSet;
import com.github.mikephil.charting.highlight.Highlight;
import com.github.mikephil.charting.interfaces.datasets.ILineDataSet;
import com.github.mikephil.charting.listener.ChartTouchListener;
import com.github.mikephil.charting.listener.OnChartGestureListener;
import com.github.mikephil.charting.listener.OnChartValueSelectedListener;
import com.github.mikephil.charting.utils.Utils;

import java.util.ArrayList;


public class MainActivity extends FragmentActivity implements SeekBar.OnSeekBarChangeListener,OnChartGestureListener,OnChartValueSelectedListener{

    private LineChart mChart;
    public static TextView tv;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        //设置窗体全屏
        getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,WindowManager.LayoutParams.FLAG_FULLSCREEN);

        setContentView(R.layout.activity_main);

        tv = (TextView) findViewById(R.id.text);

        mChart = (LineChart)findViewById(R.id.linechart);
        mChart.setOnChartGestureListener(this);
        mChart.setOnChartValueSelectedListener(this);
        mChart.setDrawGridBackground(false);

        //no description text
        mChart.setDescription("");
        mChart.setNoDataTextDescription("没有数据");

        //enable touch gestures
        mChart.setTouchEnabled(true);

        //enable scaling and dragging
        mChart.setDragEnabled(true);
        mChart.setScaleEnabled(true);
//        mChart.setScaleXEnabled(true);
//        mChart.setScaleYEnabled(true);

        //if disable , scaling can be done on x- and y-axis separately
        mChart.setPinchZoom(true);

        //set an alternative background color
//        mChart.setBackgroundColor(Color.GRAY);

        //create a custom MarkerView (extend MarkerView) and specify the layout
        //to use for it
        MyMarkerView mv = new MyMarkerView(this,R.layout.custom_marker_view);

        //set the marker to the chart
        mChart.setMarkerView(mv);
        //x-axis limit line
        LimitLine llXAxis = new LimitLine(10f,"Index 10");
        llXAxis.setLineWidth(4f);
        llXAxis.enableDashedLine(10f, 10f, 10f);
        llXAxis.setLabelPosition(LimitLine.LimitLabelPosition.RIGHT_BOTTOM);
        llXAxis.setTextSize(10f);

        XAxis xAxis = mChart.getXAxis();
//        xAxis.setValueFormatter(new MyCustomXAxisValueFormater());
//        xAxis.addLimitLine(llXAxis);//add x-axis limit line

        LimitLine ll1 = new LimitLine(130f,"Upper Limit");
        ll1.setLineWidth(4f);
        ll1.enableDashedLine(10f, 10f, 10f);
        ll1.setLabelPosition(LimitLine.LimitLabelPosition.RIGHT_TOP);
        ll1.setTextSize(10f);
//        ll1.setTypeface(tf);

        LimitLine ll2 = new LimitLine(-30f,"Lower Limit");
        ll2.setLineWidth(4f);
        ll2.enableDashedLine(10f, 10f, 10f);
        ll2.setLabelPosition(LimitLine.LimitLabelPosition.RIGHT_BOTTOM);
        ll2.setTextSize(10f);
//        ll1.setTypeface(tf);

        YAxis leftAxis = mChart.getAxisLeft();
        leftAxis.removeAllLimitLines();//reset all limit lines to avoid overlapping lines
        leftAxis.addLimitLine(ll1);
        leftAxis.addLimitLine(ll2);
        leftAxis.setAxisMaxValue(220f);
        leftAxis.setAxisMinValue(-50f);
//        leftAxis.setYOffset(20f);
        leftAxis.enableGridDashedLine(10f,10f,10f);
        leftAxis.setDrawZeroLine(false);

        //limit lines are drawn behind data(and not on top)
        leftAxis.setDrawLimitLinesBehindData(true);

        mChart.getAxisRight().setEnabled(false);

//        mChart.getViewPortHandler().setMaximumScaleY(2f);
//        mChart.getViewPortHandler().setMaximumScaleX(2f);

        //add data
        setData(45,100);

//        mChart.setVisibleXRange(20);
//        mChart.setVisibleYRange(20f, AxisDependency.LEFT);
//        mChart.centerView(20,50, AxisDependency.LEFT);

        mChart.animateX(2500, Easing.EasingOption.EaseInOutQuad);
//        mChart.invalidate();

        //get the legend(only possible after setting data)
        Legend l = mChart.getLegend();

        //modify the legend...
//        l.setPosition(Legend.LegendPosition.LEFT_OF_CHART);
        l.setForm(Legend.LegendForm.LINE);

        //dont forget to refresh the drawing
//        mChart.invalidate();

    }


    private void setData(int count,float range){
        ArrayList<String> xVals = new ArrayList<String>();
        for (int i = 0;i<count;i++){
            xVals.add((i)+"");
        }

        ArrayList<Entry> yVals = new ArrayList<Entry>();

        for (int i = 0;i < count;i++){
            float mult = (range + 1);
            float val = (float)(Math.random() * mult)+3;//+(float)
            //((mult *
            // 0.1)/10;
            yVals.add(new Entry(val,i));
        }

        LineDataSet set1;

        if (mChart.getData() != null && mChart.getData().getDataSetCount() >0){
            set1 = (LineDataSet) mChart.getData().getDataSetByIndex(0);
            set1.setYVals(yVals);
            mChart.getData().setXVals(xVals);
            mChart.notifyDataSetChanged();
        }else {
            //create a dataset and give it a type
            set1 = new LineDataSet(yVals,"DataSet 1");

//            set1.setFillAlpha(110);
//            set1.setFillColor(Color.RED);

            //set the line to be drawn like this"-----"
            set1.enableDashedLine(10f, 5f, 0f);
            set1.enableDashedHighlightLine(10f, 5f, 0f);
            set1.setColor(Color.BLACK);
            set1.setCircleColor(Color.BLACK);
            set1.setLineWidth(1f);
            set1.setCircleRadius(3f);
            set1.setDrawCircleHole(false);
            set1.setValueTextSize(9f);
            set1.setDrawFilled(true);

            if (Utils.getSDKInt() >= 18){
                //fill drawble only supported on api level 18 and above
                Drawable drawable = ContextCompat.getDrawable(this,R.drawable.fade_red);
                set1.setFillDrawable(drawable);
            }else {
                set1.setFillColor(Color.BLACK);
            }

            ArrayList<ILineDataSet> dataSets = new ArrayList<ILineDataSet>();
            dataSets.add(set1);//add the datasets

            //create a data object with the datasets
            LineData data = new LineData(xVals,dataSets);

            //set data
            mChart.setData(data);
        }
    }
    @Override
    public void onWindowFocusChanged(boolean hasFocus) {
        super.onWindowFocusChanged(hasFocus);
    }

    @Override
    public void onChartGestureStart(MotionEvent me, ChartTouchListener.ChartGesture lastPerformedGesture) {
        Log.i("Gestue","START, X"+me.getX()+",Y:"+me.getY());
    }

    @Override
    public void onChartGestureEnd(MotionEvent me, ChartTouchListener.ChartGesture lastPerformedGesture) {
        Log.i("Gestue", "END, lastGesture:" + lastPerformedGesture);

        //un-highlight values after the gesture is finish and no single-tap
        if (lastPerformedGesture != ChartTouchListener.ChartGesture.SINGLE_TAP)
            mChart.highlightValue(null); // or highlightTouch(null) for callback to onNothingSelected(...)
    }

    @Override
    public void onChartLongPressed(MotionEvent me) {
        Log.i("LongPress","Chart longpressed.");
    }

    @Override
    public void onChartDoubleTapped(MotionEvent me) {
        Log.i("DoubleTap","Chart double-tapped.");

    }

    @Override
    public void onChartSingleTapped(MotionEvent me) {
        Log.i("SingleTap","Chart single-tapped.");

    }

    @Override
    public void onChartFling(MotionEvent me1, MotionEvent me2, float velocityX, float velocityY) {
        Log.i("Fling","Chart flinged. VeloX:"+velocityX+",VeloY:"+velocityY);
    }

    @Override
    public void onChartScale(MotionEvent me, float scaleX, float scaleY) {
        Log.i("Scale / Zoom","ScaleX:"+scaleX+",ScaleY:"+scaleY);
    }

    @Override
    public void onChartTranslate(MotionEvent me, float dX, float dY) {
        Log.i("Translate / Move","dX:"+dX+",dY:"+dY);
    }

    @Override
    public void onValueSelected(Entry e, int dataSetIndex, Highlight h) {
        Log.i("Entry selected",e.toString());
        Log.i("LOWHIGH","low:"+mChart.getLowestVisibleXIndex()+",high:"+mChart.getHighestVisibleXIndex());
        Log.i("MIN MAX","xmin:"+mChart.getXChartMin()+",xmax:"+mChart.getXChartMax()+",ymin:"+mChart.getYChartMin()+",ymax:"+mChart.getYChartMax());
    }

    @Override
    public void onNothingSelected() {
        Log.i("Nothing selected","Nothing selected.");
    }

    @Override
    public void onProgressChanged(SeekBar seekBar, int i, boolean b) {

    }

    @Override
    public void onStartTrackingTouch(SeekBar seekBar) {

    }

    @Override
    public void onStopTrackingTouch(SeekBar seekBar) {

    }
}
